<template>
  <div>
    <div class="main_operation">
      <!-- <div class="operation_left">
                <h3 class="title" style="min-width: 100px">历史曲线</h3>
            </div> -->
      <div class="operation_right">
        <a-select allowClear :getPopupContainer="triggerNode => triggerNode.parentNode" class="mr10" style="width: 200px" v-model="formList.equipment_id" placeholder="设备名称">
          <a-select-option v-for="item in equipmentData" :value="item.id" :key="item.id">{{item.name}}</a-select-option>
        </a-select>
        <a-range-picker class="mr10" @ok="onOk" :showTime="{defaultValue:[moment('00:00:00','HH:mm:ss'), moment('00:00:00','HH:mm:ss')] }" format="YYYY-MM-DD HH:mm:ss" :getCalendarContainer="triggerNode => triggerNode.parentNode" :placeholder="['开始时间', '结束时间']" />
        <a-button class="mr10" type="primary" @click="equipChange">搜索</a-button>
        <a-button type="primary" @click="downloadBtn">下载数据</a-button>
      </div>
    </div>
    <div class="main">
      <a-row>
        <a-col :md="15" :xs="24">
          <!-- <div style="max-height: 554px; overflow:auto;"> -->
            <div ref="consume" style="width:100%; height:300px;"></div><!-- 能耗 -->
            <div ref="yield" style="width:100%; height:300px;"></div><!-- 产量 -->
            <div ref="average" style="width:100%; height:300px;"></div><!-- 平均能耗 -->
            <div ref="vehicle" style="width:100%; height:300px;"></div><!-- 进车数 -->
          <!-- </div> -->
        </a-col>
        <a-col :md="9" :xs="24">
          <a-table :pagination="false" size="small" :loading="tableLoad" :columns="Fields" :dataSource="dataLists.data"
          :rowKey="record => record.id">
          </a-table>
          <div class="pageBox">
            <a-pagination :total="dataLists.total|| 0" :showTotal="total => `共 ${total} 条数据`" :pageSize="dataLists.per_page || 1"
            :defaultCurrent=1  @change="pageChange" />
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<script>
// dataCenterStatistics
// import { ChartCard, MiniArea, MiniBar, MiniProgress, RankList, Bar, Trend, NumberInfo, MiniSmoothArea } from '@/components'
import { mapState, mapActions } from 'vuex';
import moment from 'moment';

export default {
  name: 'Statistics',
  components: {
    // ChartCard
  },
  data() {
    return {
      /* 通用模块 */
      // 列表
      tableLoad: false, // 列表loading状态
      formList: { // 列表信息
        equipment_id: undefined,
        page: 1,
      },
      selectedRowKeys: [], // 勾选的id
      /* 通用模块end */

      // 折线图
      consumeData: {},
      yieldData: {},
      averageData: {},
      vehicleData: {},
    };
  },
  mounted() {
    this.equipmentAll();
    this.getChart();
    if (this.$route.query.equipmentId) {
      this.formList.equipment_id = Number(this.$route.query.equipmentId);
      this.changeData();
    }
  },
  computed: {
    ...mapState({
      Fields: state => state.dataCenterStatistics.Fields,
      dataLists: state => state.dataCenterStatistics.dataLists,
      requestCode: state => state.dataCenterStatistics.requestCode,
      equipmentData: state => state.equipment.equipmentData,
    }),
  },
  watch: {
    dataLists(newData) {
      if (newData.data.length) {
        this.drawLine();
      }
    },
    equipmentData() {
      if (!this.$route.query.equipmentId) {
        this.formList.equipment_id = this.equipmentData[0].id;
        this.equipChange();
      }
    },
  },
  methods: {
    // 按钮点击触发
    downloadBtn() {
      console.log('点我下载');
      // 载
      this.exportData(this.formList).then((res) => {
        console.log(res);
        const execlName = '统计报表导出';
        if (res.data.type == 'application/json') {
				            this.$message.error('查询数据为空');
				        } else {
				            const blob = new Blob(
				                [res.data], {
				                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
				                },
          );
				            const aEle = document.createElement('a'); // 创建a标签
				            const href = window.URL.createObjectURL(blob); // 创建下载的链接
				            aEle.href = href;
				            aEle.download = execlName; // 下载后文件名
				            document.body.appendChild(aEle);
				            aEle.click(); // 点击下载
				            document.body.removeChild(aEle); // 下载完成移除元素
				            window.URL.revokeObjectURL(href); // 释放掉blob对象

				            this.$message.success('导出成功');
				        }
      });
    },
    moment,
    onChange(value, dateString) {
      console.log('Selected Time: ', value);
      console.log('Formatted Selected Time: ', dateString);
    },
    onOk(value) {
      const timeA = moment(value[0]._d).format('YYYY-MM-DD HH:mm:ss');
      const timeB = moment(value[1]._d).format('YYYY-MM-DD HH:mm:ss');
      this.formList.statistics_date_start = timeA;
      this.formList.statistics_date_end = timeB;
    },
    // 设备名称变化
    equipChange(val) {
      this.changeData();
    },
    ...mapActions({
      getLists: 'dataCenterStatistics/getLists', // 列表
      equipmentAll: 'equipment/equipmentAll', // 所有设备名称
      exportData: 'equipment/exportData', // 导出统计报表
    }),
    /* 通用模块 */
    // 勾选
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    // 重新获取列表数据
    changeData() {
      this.getLists(false);// 清空
      this.tableLoad = true;
      this.getLists(this.formList);
      setTimeout(() => {
        this.tableLoad = false;
      }, 1000);
    },
    // 页码
    pageChange(page) {
      this.formList.page = page;
      this.getLists(this.formList);
    },
    /* 通用模块end */
    drawLine() {
      // 基于准本好的DOM，初始化echarts实例
      const consumeline = this.$echarts.init(this.$refs.consume);
      const yieldline = this.$echarts.init(this.$refs.yield);
      const averageline = this.$echarts.init(this.$refs.average);
      const vehicle = this.$echarts.init(this.$refs.vehicle);
      // //绘制图表
      consumeline.setOption({
        	xAxis: [
        		{
        			data: this.dataLists.chartData.date,
        		},
        	],
        	series: {
          label: {
            normal: {
              show: false,
            },
          },
        		data: this.dataLists.chartData.consumptionData,
        	},
      });
      yieldline.setOption({
        	xAxis: [
        		{
        			data: this.dataLists.chartData.date,
        		},
        	],
        	series: {
          label: {
            normal: {
              show: false,
            },
          },
        		data: this.dataLists.chartData.yieldData,
        	},
      });
      averageline.setOption({
        	xAxis: [
        		{
        			data: this.dataLists.chartData.date,
        		},
        	],
        	series: {
          label: {
            normal: {
              show: false,
            },
          },
        		data: this.dataLists.chartData.averageData,
        	},
      });
      vehicle.setOption({
        	xAxis: [
        		{
        			data: this.dataLists.chartData.date,
        		},
        	],
        	series: {
          label: {
            normal: {
              show: false,
            },
          },
        		data: this.dataLists.chartData.vehicleData,
        	},
      });
    },
    getChart() {
      this.consumeData = {
        title: {
          text: '能耗',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        legend: {
          data: ['能耗'],
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        grid: {
          left: '8%',
          // containLabel: true
        },
        xAxis: {
          name: '时间',
          inverse: false, // 渲染顺序
          // boundaryGap: false,
          data: [],
        },
        yAxis: {
          name: '能耗',
        },
        series: [{
          name: '能耗',
          type: 'line', // 设置图表主题
          data: [],
          label: {
              	normal: {
              		show: true,
              		color: '#666',
              		position: 'top',
              	},
          },
        }],
      },
      this.yieldData = {
        title: {
          text: '产量',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        legend: {
          data: ['产量'],
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        grid: {
          left: '8%',
          // containLabel: true
        },
        xAxis: {
          name: '时间',
          inverse: false,
          // boundaryGap: false,
          data: [],
        },
        yAxis: {
          name: '产量',
          minInterval: 1,
        },
        series: [{
          name: '产量',
          type: 'line', // 设置图表主题
          data: [],
          label: {
              	normal: {
              		show: true,
              		color: '#666',
              		position: 'top',
              	},
          },
        }],
      },
      this.vehicleData = {
        title: {
          text: '进车数',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        legend: {
          data: ['进车数'],
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        grid: {
          left: '8%',
          // containLabel: true
        },
        xAxis: {
          name: '时间',
          inverse: false,
          // boundaryGap: false,
          data: [],
        },
        yAxis: {
          name: '进车数',
          minInterval: 1,
        },
        series: [{
          name: '进车数',
          type: 'line', // 设置图表主题
          data: [],
          label: {
              	normal: {
              		show: true,
              		color: '#666',
              		position: 'top',
              	},
          },
        }],
      },
      this.averageData = {
        title: {
          text: '平均能耗',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985',
            },
          },
        },
        legend: {
          data: ['平均能耗'],
        },
        toolbox: {
          feature: {
            saveAsImage: {},
          },
        },
        grid: {
          left: '8%',
        },
        xAxis: {
          name: '时间',
          inverse: false,
          data: [],
        },
        yAxis: {
          name: '平均能耗',
        },
        series: [{
          name: '平均能耗',
          type: 'line', // 设置图表主题
          data: [],
          label: {
              	normal: {
              		show: true,
              		color: '#666',
              		position: 'top',
              	},
          },
        }],
      };
      const consumeline = this.$echarts.init(this.$refs.consume);
      const yieldline = this.$echarts.init(this.$refs.yield);
      const averageline = this.$echarts.init(this.$refs.average);
      const vehicle = this.$echarts.init(this.$refs.vehicle);
      // 绘制图表
      consumeline.setOption(this.consumeData); /* 能耗 */
      yieldline.setOption(this.yieldData); /* 产量 */
      averageline.setOption(this.averageData); /* 平均能耗 */
      vehicle.setOption(this.vehicleData); /* 进车数 */
      window.onresize = () => {
        consumeline.resize();
        yieldline.resize();
        averageline.resize();
        vehicle.resize();
      };
    },
  },
};
</script>

<style scoped>

</style>
